import random
import pygame
import pickle

SCREEN_RECT = pygame.Rect(0,0,480,700)

#游戏循环时间
FRAME_PER_SEC = 60

# 定时器----定时创建敌机
CREATE_ENEMY_EVENT = pygame.USEREVENT

#定时器----英雄定时发射子弹
HERO_FIRE_EVENT = pygame.USEREVENT +1

BG_IMG = "./images/background.png"#游戏背景图片
ENEMY_IMG = "./images/enemy1.png"#敌机图片
SUPPLY_IMG = "./images/bullet_supply.png"#导弹图片
BOMB_IMG = "./images/bomb_supply.png"#鱼雷图片
HERO_IMG = "./images/me1.png"#英雄图片
Bullet_IMG = "./images/bullet1.png"#子弹图片


class GameSprite(pygame.sprite.Sprite):
    """飞机大战游戏精灵"""

    def __init__(self,image_name,speed=1):
        #调用父类的初始化方法
        super().__init__()

        #定义对象的属性
        self.image = pygame.image.load(image_name)
        self.rect = self.image.get_rect()
        self.speed = speed

    def update(self):
        self.rect.y += self.speed

class Background(GameSprite):
    """游戏背景精灵"""
    def __init__(self,image_name=BG_IMG,speed=1,is_alt=False):
        #调用父类的初始化方法
        super().__init__(image_name,speed)
        if is_alt:
            self.rect.y = -self.rect.height

    def update(self):
        # 1、调用父类的方法实现
        super().update()

        #2、判断是否移出屏幕，如果移出屏幕，将图像设置的屏幕的上方
        if self.rect.y >= SCREEN_RECT.height:#屏幕高度
            self.rect.y = -self.rect.height#背景图高度

class Enemy(GameSprite):
    """敌机精灵"""
    def __init__(self,image_name=ENEMY_IMG,speed=1):
        #调用父类的初始化方法
        super().__init__(image_name,speed)

        #指定敌机的初始随机位置
        self.rect.x = random.randint(0, SCREEN_RECT.width - self.rect.width)
        self.rect.bottom = 0

        self.is_survive = True
        self.die_animation_count = 0
    def update(self):
        # 死了播放死亡动画，没死正常移动
        if self.is_survive:
            # 1、调用父类的方法实现
            super().update()

            # 2、判断是否飞出屏幕，如果是，需要从精灵组删除敌机
            if self.rect.y >= SCREEN_RECT.height:  # 屏幕高度
                # print("飞出屏幕，需要从精灵组删除...")
                self.kill()
        else:
            img_arr = [
                "./images/enemy1_down1.png",
                "./images/enemy1_down2.png",
                "./images/enemy1_down3.png",
                "./images/enemy1_down4.png",
            ]
            if self.die_animation_count in range(len(img_arr)):
                self.image = pygame.image.load(img_arr[self.die_animation_count])
                self.die_animation_count += 1
                hero_clock = pygame.time.Clock()
                hero_clock.tick(40)
            else:
                self.kill()
                self.is_game_over = True
    def die_animation(self):
        self.is_survive = False
    def __del__(self):
            # print("敌机挂了 %s..." % self.rect)
            pass


class Hero(GameSprite):
    """英雄精灵"""
    def __init__(self,image_name=HERO_IMG):
        #调用父类的初始化方法
        super().__init__(image_name,0)

        #指定英雄的初始位置
        self.rect.centerx = SCREEN_RECT.centerx
        self.rect.bottom = SCREEN_RECT.bottom-50

        self.is_survive = True
        self.is_game_over = False
        self.die_animation_count = 0

        self.speed_y = 0

        #创建子弹精灵组
        self.bullet = pygame.sprite.Group()

    def update(self):
        #死了播放死亡动画，没死正常移动
        if self.is_survive:
            self.rect.x += self.speed
            self.rect.y += self.speed_y

            if self.rect.y < 0:
                self.rect.y = 0
            elif self.rect.bottom >= SCREEN_RECT.bottom:
                self.rect.bottom = SCREEN_RECT.bottom-50

            if self.rect.x < 0:
                self.rect.x = 0
            elif self.rect.right >= SCREEN_RECT.right:
                self.rect.right = SCREEN_RECT.right
        else:
            img_arr = [
                "./images/me_destroy_1.png",
                "./images/me_destroy_2.png",
                "./images/me_destroy_3.png",
                "./images/me_destroy_4.png",
            ]
            if self.die_animation_count in range(len(img_arr)):
                self.image = pygame.image.load(img_arr[self.die_animation_count])
                self.die_animation_count += 1
                hero_clock = pygame.time.Clock()
                hero_clock.tick(3)
            else:
                self.kill()
                self.is_game_over = True


    def die_animation(self):
        self.is_survive = False

    #发射子弹
    def fire(self):
        for i in(0,1,2):
            #创建子弹精灵
            bullet = Bullet()

            #设置精灵的位置
            bullet.rect.bottom = self.rect.y - i * 20
            bullet.rect.centerx = self.rect.centerx

            #将精灵添加到精灵组
            self.bullet.add(bullet)

class Bullet(GameSprite):
    """子弹精灵"""
    def __init__(self,image_name=Bullet_IMG):
        #调用父类的初始化方法
        super().__init__(image_name,-2)
    def update(self):
        super().update()
        if self.rect.bottom <= 0:
            self.kill()

class TextSprite(pygame.sprite.Sprite):
    """文字精灵"""
    def __init__(self, text, mod=0):
        super().__init__()
        self.image = self._render_text(text)
        self.rect = self.image.get_rect()

    def _render_text(self, text):
        pygame.font.init()
        font = pygame.font.SysFont('SimHei', 20)
        text_surface = font.render(text, True, (0, 0, 0))

        # text_surface.set_colorkey((0, 0, 0))  # 设置透明色
        return text_surface


class ScoreClass(object):
    """文字精灵"""

    def __init__(self):
        super().__init__()

    # 加载分数的函数
    @staticmethod
    def load_score():
        try:
            with open('score.pkl', 'rb') as file:
                return pickle.load(file)
        except (IOError, pickle.PickleError):
            return 0

    # 保存分数的函数
    def save_score(self,new_score):
        this_score = self.load_score()
        if this_score < new_score:
            with open('score.pkl', 'wb') as file:
                pickle.dump(new_score, file)
